<?php

namespace app\api\controller;

use app\common\controller\Api;

/**
 * 文章接口
 */
class Article extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 文章分类列表
     *
     */
    public function article_category_list()
    {
        if (\request()->isGet())
        {
            $list = Model('article_category')->select();

            if(!empty($list))
            {
                foreach($list as $key => $value)
                {
                    $list[$key]['created_time'] = date('Y-m-d H:i:s',$value['created_time']);
                    $list[$key]['updated_time'] = date('Y-m-d H:i:s',$value['updated_time']);
                }
            }

            $this->success("ok", $list);
        }
    }

    /**
     * 文章列表
     *
     */
    public function article_list()
    {
        if (\request()->isGet())
        {

            $article_category_id = (int)$this->request->get('article_category_id',0);
            $page = (int)$this->request->get('page');

            $page = $page <1 ? 1 : $page;
            $limit = 10;

            $where = [];
            if(!empty($article_category_id))
            {
                $where['category_id'] = $article_category_id;
            }

            $offset = ($page - 1) * $limit;
            $list = Model('article')->where($where)->order('id desc')->limit($offset,$limit)->select();
            $total = Model('article')->where($where)->order('id desc')->limit($offset,$limit)->count();

            if(!empty($list))
            {
                foreach($list as $key => $value)
                {
                    $list[$key]['created_time'] = date('Y-m-d H:i',$value['created_time']);
                    $list[$key]['updated_time'] = date('Y-m-d H:i',$value['updated_time']);
                }
            }

            $data = [
                'total' => $total,
                'per_page' => $limit,
                'current_page' => $page,
                'last_page' => ceil($total/$limit),
                'data' => $list
            ];
            $this->success("ok", $data);
        }
    }

    /**
     * 文章详情
     *
     */
    public function article_detail()
    {
        if (\request()->isGet())
        {

            $id = (int)$this->request->get('id',0);

            $article = Model('article')->find($id);

            if(!empty($article))
            {
                $article['category'] = Model('article_category')->find($article['category_id']);
                $article['created_time'] = date('Y-m-d H:i',$article['created_time']);
                $article['updated_time'] = date('Y-m-d H:i',$article['updated_time']);
            }
            $this->success("ok", $article);
        }
    }
}